package org.example.Swing.handler;


import org.example.Swing.xiangmu.login.MainView;
import org.example.Swing.xiangmu.login.UpdateView;
import org.example.controller.GradeController;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class UpdateHandler extends KeyAdapter implements ActionListener {
    private final UpdateView updateView;

    public UpdateHandler(UpdateView updateView) {
        this.updateView = updateView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        System.out.println(text);
        if ("修改成绩".equals(text)) {
            int option = JOptionPane.showConfirmDialog(updateView, "你确认要修改该学生的成绩吗?", "是否修改", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                update();
            }
        }
    }

    public void update() {
        GradeController gradeController = new GradeController();
        String stuId = updateView.getStuId().getText();
        String scorePs = updateView.getPsTxt().getText();
        String scoreKs = updateView.getKsTxt().getText();
        int courseId = updateView.getCourseId();
        double score = Double.parseDouble(scorePs);
        double scoreK = Double.parseDouble(scoreKs);
        if (stuId != null && score != 0 && scoreK != 0 && courseId != 0) {
            int i = gradeController.updateScore(stuId, score, scoreK, courseId);
            if (i > 0) {
                JOptionPane.showMessageDialog(updateView, "修改成功！");
                updateView.dispose();
                new MainView();
            } else {
                JOptionPane.showMessageDialog(updateView, "修改失败！！");
            }
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            update();
        }
    }
}
